﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    public partial class SpecialListPage : PhoneApplicationPage
    {
        private int specialId = 0;
        private string speciaTitle = string.Empty;
        private int pageIndex = 1;
        private bool IsLastPage = false;
        private ComicsList currentSelectedItem = null;
        private ObservableCollection<ComicsList> hotComics = new ObservableCollection<ComicsList>();

        public SpecialListPage()
        {
            InitializeComponent();
            this.hotComics = new LocalHotComicHelper().GetHotComics();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (!base.NavigationContext.QueryString.ContainsKey("specialId"))
            {
                base.NavigationService.GoBack();
                return;
            }
            string value = string.Empty;
            base.NavigationContext.QueryString.TryGetValue("specialId", out value);
            if (string.IsNullOrWhiteSpace(value))
            {
                base.NavigationService.GoBack();
                return;
            }
            int.TryParse(value, out specialId);
            if (specialId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("title", out speciaTitle);
            this.txtTitle.Text = speciaTitle;
            LoadSpecialData(specialId);
        }


        void LoadSpecialData(int specialId, int pageIndex = 1)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicslist_v2", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl + "\t,PageIndex=" + pageIndex, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("sort", 0);
            parameters.Add("pageno", pageIndex);
            parameters.Add("pagesize", 20);
            parameters.Add("special", specialId.ToString());
            //
            PostClientHelper proxy = new PostClientHelper(parameters);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(string.Concat(requestUrl, proxy.PostData.ToString())));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonChannelMoreBase>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.ComicsList != null && rootCharacterString.Info.ComicsList.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.ComicsList;
                    if (items != null && items.Count > 0)
                    {
                        this.BindSpecialData(items);
                    }
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        return;
                    }

                    #region 获取结果处理
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        LogHelper.LogError("Result is empty.");
                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                        return;
                    }
                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                    if (result.IndexOf("\"comicsList\":{}") >= 0)
                    {
                        IsLastPage = true;
                        return;
                    }
                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonChannelMoreBase>(result);
                    if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.ComicsList != null && rootCharacterString.Info.ComicsList.Count > 0))
                    {
                        //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                    }
                    else
                    {
                        var items = rootCharacterString.Info.ComicsList;
                        if (items != null && items.Count > 0)
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            this.BindSpecialData(items);
                        }
                    }

                    #endregion 获取结果处理
                }
                catch (Exception err)
                {
                }
                finally
                {
                    this.psbStatus.CloseStatusBar();
                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }

        void BindSpecialData(ObservableCollection<ComicsList> items)
        {
            if (!(items != null && items.Count > 0))
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                //
                //foreach (var item in items)
                //{
                //    if(item == null)
                //        continue;
                //    var hotComic = (from p in this.hotComics where p.BigbookId == item.BigbookId select p).FirstOrDefault<ComicsList>();
                //    if (hotComic != null)
                //        item.IsHotComic = true;
                //    else
                //        item.IsHotComic = false;
                //}
                //
                if (this.lls.ItemsSource != null && this.lls.ItemsSource.Count > 0)
                {
                    foreach (var item in items)
                    {
                        this.lls.ItemsSource.Add(item);
                    }
                }
                else
                {
                    this.lls.ItemsSource = items;
                }
            });
        }


        // 数据加载的标识
        public bool IsLoading = false;
        // 线程锁的对象
        private object o = new object();
        private void lls_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            // 因为该事件会被多个线程进入，所以添加线程锁，控制下面的代码只能单个线程去执行
            lock (o)
            {
                if (IsLoading)
                    return;
                if (e.ItemKind != LongListSelectorItemKind.Item)
                    return;

                //
                MarkHotComicFlag(e.Container);
                //
                currentSelectedItem = e.Container.Content as ComicsList;
                int selectedIndex = this.lls.ItemsSource.IndexOf(currentSelectedItem);
                int total = this.lls.ItemsSource.Count;
                if (total - selectedIndex <= 2)
                {
                    // 设置IsLoading为true，在加载数据的过程中，禁止多次进入
                    IsLoading = true;
                    if (IsLastPage)
                    {
                        //this.statusBar.OpenStatusBar(AppResources.DataNoMore);
                        //this.statusBar.CloseStatusBar();
                        MessageToastManager.Show("没有更多数据了！");
                        // 修改加载的状态
                        IsLoading = false;
                    }
                    else
                    {
                        this.pageIndex += 1;
                        this.LoadSpecialData(this.specialId, pageIndex);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                }
            }
        }

        void MarkHotComicFlag(ContentPresenter contentPresenter)
        { 
             try
            {
                  var comic = contentPresenter.Content as ComicsList;
                 if(comic == null)
                     return;
                var images = Helper.FindChildren<Image>(contentPresenter);
                if (!(images != null && images.Count() > 0))
                    return;

                foreach (Image image in images)
                {
                    if (image == null)
                        continue;
                    if ("imageHotFlag".Equals(image.Name))
                    {
                        var item =(from p in this.hotComics where p.BigbookId == comic.BigbookId select p).FirstOrDefault<ComicsList>();
                        if(item != null)
                            image.Visibility =  System.Windows.Visibility.Visible;
                        else
                            image.Visibility =  System.Windows.Visibility.Collapsed;
                    }
                }
            }
            catch { }
        }

        private void lls_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ComicsList item = this.lls.SelectedItem as ComicsList;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.BigbookId));
            }
        }

        private void Grid_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Complete();
            if (e.CumulativeManipulation.Translation.Y > 0)
            {
                //从下往上拉时不处理
                return;
            }

            if (IsLastPage)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    Helper.PageShowDataNoMore<ComicsList>(sender, this.lls);
                });
            }
        }
    }
}